package com.k.activemq.openwire3;

import com.k.platform.util.DateUtil;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.time.ZoneId;

public class Sub {

    public static void main(String[] args) {
        System.out.println("mq main start");
//        String url = "failover:(tcp://primary:61616,tcp://secondary:61616)?randomize=false";
        String url = "tcp://192.168.0.169:22000";
        url = "tcp://localhost:61616";
        String username = "admin";
        String password = "admin";//""Command_123";
        String topic = "ljw-topic";//""topic_test_1103";
        boolean pubSubDomain = true;
        ActiveMQConnectionFactory connectionFactory = null;
        Connection connection = null;
        Session session = null;
        MessageConsumer consumer = null;
        try {
            // ConnectionFactory
            connectionFactory = new ActiveMQConnectionFactory(url);
            // 持久订阅需要设置
            connectionFactory.setClientID("cid_20231106");
            // Connection
            connection = connectionFactory.createConnection(username, password);
            connection.start();
            // Session
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            // 目的地
            Destination destination = pubSubDomain ? session.createTopic(topic) : session.createQueue(topic);
            // 消费者
            consumer = session.createConsumer(destination);
            // 消费者的监听程序
            MessageListener messageListener = new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    System.out.println(DateUtil.nowStr(DateUtil.PATTERN_SS, ZoneId.of("GMT+8")) + "监听到一条消息：");
                    System.out.println(Thread.currentThread() + ": message:" + message);
                    PubSubUtil.formatResponse(message);
                    System.out.println("监听完成！");
                }
            };
            // 消费者 - 添加监听程序
            consumer.setMessageListener(messageListener);
        } catch (JMSException e) {
            e.printStackTrace();
        }
        System.out.println("mq main finish");
    }
}
